<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>自动相册上传</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .content {
            padding: 30px;
        }

        .control-section {
            margin-bottom: 30px;
            text-align: center;
        }

        .btn {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 50px;
            font-size: 1.1em;
            cursor: pointer;
            margin: 10px;
            transition: all 0.3s ease;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .btn:disabled {
            background: #6c757d;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .btn-success {
            background: linear-gradient(45deg, #28a745, #20c997);
        }

        .btn-warning {
            background: linear-gradient(45deg, #ffc107, #fd7e14);
        }

        .btn-danger {
            background: linear-gradient(45deg, #dc3545, #e74c3c);
        }

        .stats-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin: 20px 0;
            text-align: center;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 20px;
            margin-top: 15px;
        }

        .stat-item {
            background: white;
            padding: 15px;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .stat-number {
            font-size: 2em;
            font-weight: bold;
            color: #667eea;
        }

        .stat-label {
            color: #666;
            margin-top: 5px;
        }

        .progress-section {
            margin: 20px 0;
        }

        .progress-bar {
            width: 100%;
            height: 20px;
            background: #e9ecef;
            border-radius: 10px;
            overflow: hidden;
            margin: 10px 0;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(45deg, #667eea, #764ba2);
            width: 0%;
            transition: width 0.3s ease;
        }

        .batch-info {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            color: #856404;
            padding: 15px;
            border-radius: 10px;
            margin: 20px 0;
        }

        .status-section {
            margin: 20px 0;
            max-height: 300px;
            overflow-y: auto;
        }

        .status-item {
            padding: 10px;
            margin: 5px 0;
            border-radius: 5px;
            border-left: 4px solid #28a745;
            background: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .status-item.error {
            border-left-color: #dc3545;
            background: #fff5f5;
        }

        .status-item.warning {
            border-left-color: #ffc107;
            background: #fffbf0;
        }

        .gallery-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }

        .gallery-item {
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }

        .gallery-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.2);
        }

        .gallery-item img {
            width: 100%;
            height: 200px;
            object-fit: cover;
        }

        .gallery-item .filename {
            padding: 10px;
            background: white;
            font-size: 0.9em;
            color: #666;
            text-align: center;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .mobile-tips {
            background: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
            padding: 15px;
            border-radius: 10px;
            margin: 20px 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 自动相册上传</h1>
            <p>自动获取手机相册并分页上传</p>
        </div>

        <div class="content">
            <!-- 移动端提示 -->
            <div class="mobile-tips">
                <strong>📱 自动相册功能：</strong><br>
                1. 点击"开始自动上传"按钮<br>
                2. 系统自动获取手机相册<br>
                3. 每批处理10张图片<br>
                4. 自动一张一张上传到服务器
            </div>

            <!-- 控制区域 -->
            <div class="control-section">
                <button id="startBtn" class="btn btn-success">
                    🚀 开始自动上传
                </button>
                <button id="pauseBtn" class="btn btn-warning" disabled>
                    ⏸️ 暂停上传
                </button>
                <button id="stopBtn" class="btn btn-danger" disabled>
                    🛑 停止上传
                </button>
                <button id="refreshBtn" class="btn">
                    🔄 刷新服务器相册
                </button>
            </div>

            <!-- 统计信息 -->
            <div class="stats-section">
                <h3>📊 上传统计</h3>
                <div class="stats-grid">
                    <div class="stat-item">
                        <div class="stat-number" id="totalImages">0</div>
                        <div class="stat-label">总图片数</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number" id="uploadedImages">0</div>
                        <div class="stat-label">已上传</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number" id="failedImages">0</div>
                        <div class="stat-label">上传失败</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number" id="currentBatch">0</div>
                        <div class="stat-label">当前批次</div>
                    </div>
                </div>
            </div>

            <!-- 批次信息 -->
            <div class="batch-info" id="batchInfo" style="display: none;">
                <strong>📦 当前批次信息：</strong><br>
                <span id="batchDetails">正在处理第 1 批，共 10 张图片</span>
            </div>

            <!-- 加载状态 -->
            <div id="loading" class="loading">
                <div class="spinner"></div>
                <p>正在自动获取相册...</p>
            </div>

            <!-- 进度条 -->
            <div class="progress-section" id="progressSection" style="display: none;">
                <h3>📈 上传进度</h3>
                <div class="progress-bar">
                    <div class="progress-fill" id="progressFill"></div>
                </div>
                <p id="progressText">0%</p>
            </div>

            <!-- 状态信息 -->
            <div class="status-section" id="statusSection" style="display: none;">
                <h3>📋 上传状态</h3>
                <div id="statusList"></div>
            </div>

            <!-- 服务器相册展示 -->
            <div class="gallery-section">
                <h3>🖼️ 服务器相册</h3>
                <div class="gallery-grid" id="galleryGrid"></div>
            </div>
        </div>
    </div>

    <script>
        class AutoAlbumUploader {
            constructor() {
                this.uploadPath = '/api/pic';
                this.batchSize = 10; // 每批处理10张图片
                this.isUploading = false;
                this.isPaused = false;
                this.totalImages = 0;
                this.uploadedImages = 0;
                this.failedImages = 0;
                this.currentBatch = 0;
                this.allImages = [];
                this.currentBatchImages = [];
                
                this.initElements();
                this.bindEvents();
                this.loadGallery();
            }

            initElements() {
                this.startBtn = document.getElementById('startBtn');
                this.pauseBtn = document.getElementById('pauseBtn');
                this.stopBtn = document.getElementById('stopBtn');
                this.refreshBtn = document.getElementById('refreshBtn');
                this.totalImagesEl = document.getElementById('totalImages');
                this.uploadedImagesEl = document.getElementById('uploadedImages');
                this.failedImagesEl = document.getElementById('failedImages');
                this.currentBatchEl = document.getElementById('currentBatch');
                this.batchInfo = document.getElementById('batchInfo');
                this.batchDetails = document.getElementById('batchDetails');
                this.progressSection = document.getElementById('progressSection');
                this.progressFill = document.getElementById('progressFill');
                this.progressText = document.getElementById('progressText');
                this.statusSection = document.getElementById('statusSection');
                this.statusList = document.getElementById('statusList');
                this.galleryGrid = document.getElementById('galleryGrid');
                this.loading = document.getElementById('loading');
            }

            bindEvents() {
                this.startBtn.addEventListener('click', () => this.startAutoUpload());
                this.pauseBtn.addEventListener('click', () => this.pauseUpload());
                this.stopBtn.addEventListener('click', () => this.stopUpload());
                this.refreshBtn.addEventListener('click', () => this.loadGallery());
            }

            async startAutoUpload() {
                if (this.isUploading) return;

                this.isUploading = true;
                this.isPaused = false;
                this.resetStats();
                this.showLoading(true);
                this.showProgress();
                this.showStatusSection();
                this.updateButtons();

                try {
                    // 模拟获取手机相册
                    await this.getPhoneAlbum();
                    
                    if (this.allImages.length === 0) {
                        this.showStatus('未找到图片或无法访问相册', 'warning');
                        this.stopUpload();
                        return;
                    }

                    this.showStatus(`成功获取 ${this.allImages.length} 张图片，开始分页上传`, 'success');
                    this.updateStats();
                    
                    // 开始分页上传
                    await this.processBatches();
                    
                } catch (error) {
                    this.showStatus(`获取相册失败: ${error.message}`, 'error');
                    this.stopUpload();
                } finally {
                    this.showLoading(false);
                }
            }

            async getPhoneAlbum() {
                // 模拟获取手机相册的过程
                this.showStatus('正在获取手机相册...', 'info');
                
                // 这里应该调用真实的手机相册API
                // 由于浏览器安全限制，我们使用模拟数据
                await this.simulateAlbumAccess();
                
                this.showStatus(`成功获取相册，共 ${this.allImages.length} 张图片`, 'success');
            }

            async simulateAlbumAccess() {
                // 模拟延迟
                await this.delay(2000);
                
                // 模拟相册数据（实际应用中这里应该调用真实的相册API）
                const mockImages = [];
                const imageCount = Math.floor(Math.random() * 50) + 20; // 20-70张图片
                
                for (let i = 0; i < imageCount; i++) {
                    mockImages.push({
                        id: i,
                        name: `photo_${i + 1}.jpg`,
                        size: Math.floor(Math.random() * 5000000) + 1000000, // 1-6MB
                        type: 'image/jpeg',
                        lastModified: Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000 // 最近30天内
                    });
                }
                
                this.allImages = mockImages;
                this.totalImages = mockImages.length;
            }

            async processBatches() {
                const totalBatches = Math.ceil(this.allImages.length / this.batchSize);
                
                for (let batchIndex = 0; batchIndex < totalBatches; batchIndex++) {
                    if (!this.isUploading || this.isPaused) break;
                    
                    this.currentBatch = batchIndex + 1;
                    this.currentBatchImages = this.allImages.slice(
                        batchIndex * this.batchSize, 
                        (batchIndex + 1) * this.batchSize
                    );
                    
                    this.updateStats();
                    this.showBatchInfo();
                    
                    this.showStatus(`开始处理第 ${this.currentBatch} 批，共 ${this.currentBatchImages.length} 张图片`, 'info');
                    
                    // 处理当前批次
                    await this.processCurrentBatch();
                    
                    // 批次间延迟
                    if (batchIndex < totalBatches - 1) {
                        await this.delay(1000);
                    }
                }
                
                if (this.isUploading) {
                    this.showStatus('所有批次处理完成！', 'success');
                    this.loadGallery();
                }
            }

            async processCurrentBatch() {
                for (let i = 0; i < this.currentBatchImages.length; i++) {
                    if (!this.isUploading || this.isPaused) break;
                    
                    const image = this.currentBatchImages[i];
                    this.showStatus(`正在上传: ${image.name}`, 'info');
                    
                    try {
                        // 模拟单张图片上传
                        await this.uploadSingleImage(image);
                        this.uploadedImages++;
                        this.showStatus(`✅ 上传成功: ${image.name}`, 'success');
                    } catch (error) {
                        this.failedImages++;
                        this.showStatus(`❌ 上传失败: ${image.name} - ${error.message}`, 'error');
                    }
                    
                    this.updateStats();
                    this.updateProgress();
                    
                    // 单张图片上传间隔
                    await this.delay(500);
                }
            }

            async uploadSingleImage(image) {
                // 模拟上传过程
                await this.delay(1000 + Math.random() * 2000); // 1-3秒随机延迟
                
                // 模拟上传失败（10%概率）
                if (Math.random() < 0.1) {
                    throw new Error('网络错误');
                }
                
                // 实际应用中这里应该调用真实的上传API
                // const formData = new FormData();
                // formData.append('file', image.file);
                // const response = await fetch(`${this.uploadPath}/save`, {
                //     method: 'POST',
                //     body: formData
                // });
                // if (!response.ok) throw new Error('上传失败');
            }

            pauseUpload() {
                this.isPaused = true;
                this.showStatus('上传已暂停', 'warning');
                this.updateButtons();
            }

            stopUpload() {
                this.isUploading = false;
                this.isPaused = false;
                this.showStatus('上传已停止', 'warning');
                this.updateButtons();
                this.hideProgress();
            }

            resetStats() {
                this.uploadedImages = 0;
                this.failedImages = 0;
                this.currentBatch = 0;
                this.updateStats();
            }

            updateStats() {
                this.totalImagesEl.textContent = this.totalImages;
                this.uploadedImagesEl.textContent = this.uploadedImages;
                this.failedImagesEl.textContent = this.failedImages;
                this.currentBatchEl.textContent = this.currentBatch;
            }

            updateProgress() {
                const total = this.totalImages;
                const uploaded = this.uploadedImages + this.failedImages;
                const percentage = total > 0 ? Math.round((uploaded / total) * 100) : 0;
                
                this.progressFill.style.width = percentage + '%';
                this.progressText.textContent = `${percentage}% (${uploaded}/${total})`;
            }

            showBatchInfo() {
                this.batchInfo.style.display = 'block';
                this.batchDetails.textContent = `正在处理第 ${this.currentBatch} 批，共 ${this.currentBatchImages.length} 张图片`;
            }

            updateButtons() {
                this.startBtn.disabled = this.isUploading;
                this.pauseBtn.disabled = !this.isUploading || this.isPaused;
                this.stopBtn.disabled = !this.isUploading;
            }

            showLoading(show) {
                this.loading.style.display = show ? 'block' : 'none';
            }

            showProgress() {
                this.progressSection.style.display = 'block';
                this.progressFill.style.width = '0%';
                this.progressText.textContent = '0%';
            }

            hideProgress() {
                this.progressSection.style.display = 'none';
            }

            showStatusSection() {
                this.statusSection.style.display = 'block';
            }

            showStatus(message, type = 'success') {
                const statusItem = document.createElement('div');
                statusItem.className = `status-item ${type}`;
                statusItem.textContent = message;
                this.statusList.appendChild(statusItem);
                this.statusList.scrollTop = this.statusList.scrollHeight;
            }

            async loadGallery() {
                try {
                    const response = await fetch(`${this.uploadPath}/list`);
                    if (response.ok) {
                        const files = await response.json();
                        this.displayGallery(files);
                    } else {
                        throw new Error('获取相册列表失败');
                    }
                } catch (error) {
                    this.showStatus(`获取相册失败: ${error.message}`, 'error');
                }
            }

            displayGallery(files) {
                this.galleryGrid.innerHTML = '';
                
                if (files.length === 0) {
                    this.galleryGrid.innerHTML = '<p style="grid-column: 1/-1; text-align: center; color: #666; padding: 40px;">暂无图片</p>';
                    return;
                }

                files.forEach(filename => {
                    const galleryItem = document.createElement('div');
                    galleryItem.className = 'gallery-item';
                    galleryItem.innerHTML = `
                        <img src="/uploads/${filename}" alt="${filename}" onerror="this.src=''">
                        <div class="filename">${filename}</div>
                    `;
                    this.galleryGrid.appendChild(galleryItem);
                });
            }

            delay(ms) {
                return new Promise(resolve => setTimeout(resolve, ms));
            }
        }

        // 页面加载完成后初始化
        let uploader;
        document.addEventListener('DOMContentLoaded', () => {
            uploader = new AutoAlbumUploader();
        });
    </script>
</body>
</html>